package xianchengchi;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/6/4 8:37
 * @Description: 线程池的1个使用问题 来自于极海
 */
public class TestXianChenChi {

    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10, 1, TimeUnit.MINUTES,
            new LinkedBlockingQueue<Runnable>(100), new ThreadFactoryBuilder().setNameFormat("sync-%d").build(), new ThreadPoolExecutor.AbortPolicy());


    public static void main(String[] args) {
        moveUsers(Arrays.asList("1","2","3","4","5"));
    }

    private static void moveUsers(List<String> users){
        for (String user : users) {
            threadPoolExecutor.execute(()->{
                moveUser(user);
            });
        }
    }

    private static void moveUser(String user){
        CountDownLatch cdl = new CountDownLatch(2);
        syncBasicData(user, cdl);
        syncAccountData(user, cdl);
        check(user, cdl);
    }

    private static void syncAccountData(String user, CountDownLatch cdl) {
        threadPoolExecutor.execute(()->{
            cdl.countDown();
        });
    }

    private static void syncBasicData(String user, CountDownLatch cdl) {
        threadPoolExecutor.execute(()->{
            cdl.countDown();
        });
    }

    private static void check(String user, CountDownLatch cdl){
        try {
            cdl.await(5, TimeUnit.SECONDS);
            System.out.println(new Date() + "  " + Thread.currentThread().getName()+" check userId " + user);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


}
